<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学院管理员管理 - 推免系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background-color: #f5f5f5;
        }

        .header {
            background: #fff;
            padding: 15px 20px;
            border-bottom: 1px solid #e8e8e8;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header h1 {
            color: #333;
            font-size: 20px;
        }

        .user-info {
            color: #666;
        }

        .container {
            display: flex;
            min-height: calc(100vh - 60px);
        }

        .sidebar {
            width: 200px;
            background: #fff;
            border-right: 1px solid #e8e8e8;
            padding: 20px 0;
        }

        .menu-item {
            padding: 12px 20px;
            cursor: pointer;
            border-left: 3px solid transparent;
            color: #666;
        }

        .menu-item.active {
            background: #f0f7ff;
            border-left-color: #1890ff;
            color: #1890ff;
        }

        .menu-item:hover {
            background: #f5f5f5;
        }

        .main-content {
            flex: 1;
            padding: 20px;
            background: #fff;
            margin: 20px;
            border-radius: 6px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #e8e8e8;
        }

        .page-title {
            font-size: 18px;
            color: #333;
        }

        .breadcrumb {
            color: #666;
            font-size: 14px;
        }

        .breadcrumb a {
            color: #1890ff;
            text-decoration: none;
        }

        .breadcrumb a:hover {
            text-decoration: underline;
        }

        .actions {
            display: flex;
            gap: 10px;
        }

        .btn {
            padding: 8px 16px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            background: #fff;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-primary {
            background: #1890ff;
            color: white;
            border-color: #1890ff;
        }

        .btn-danger {
            background: #ff4d4f;
            color: white;
            border-color: #ff4d4f;
        }

        .btn:hover {
            opacity: 0.8;
        }

        .search-box {
            padding: 8px 12px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            width: 200px;
        }

        .stats {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 20px;
            border-left: 4px solid #52c41a;
        }

        .stats span {
            margin-right: 20px;
            color: #666;
        }

        .stats strong {
            color: #52c41a;
            font-size: 18px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }

        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #e8e8e8;
        }

        th {
            background: #fafafa;
            font-weight: 600;
            color: #333;
        }

        tr:hover {
            background: #f8f9fa;
        }

        .action-buttons {
            display: flex;
            gap: 8px;
        }

        .action-btn {
            padding: 4px 8px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            font-size: 12px;
        }

        .reset-btn {
            background: #1890ff;
            color: white;
        }

        .remove-btn {
            background: #ff4d4f;
            color: white;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
        }

        .modal-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 20px;
            border-radius: 6px;
            min-width: 400px;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #e8e8e8;
        }

        .close {
            font-size: 20px;
            cursor: pointer;
            color: #999;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #333;
            font-weight: 500;
        }

        .form-control {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
        }

        .form-control:focus {
            border-color: #1890ff;
            outline: none;
        }

        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
            padding-top: 15px;
            border-top: 1px solid #e8e8e8;
        }

        .empty-state {
            text-align: center;
            padding: 40px;
            color: #999;
        }

        .empty-state img {
            width: 64px;
            height: 64px;
            margin-bottom: 16px;
            opacity: 0.5;
        }

        .debug-info {
            background: #f8f9fa;
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            font-size: 12px;
            color: #666;
            display: none;
        }
    </style>
</head>
<body>
<!-- 头部导航 -->
<div class="header">
    <h1>推免系统 - 超级管理员</h1>
    <div class="user-info">
        <span>超级管理员</span>
        <button class="btn" onclick="logout()" style="margin-left: 10px;">退出登录</button>
    </div>
</div>

<!-- 主体容器 -->
<div class="container">
    <!-- 侧边栏 -->
    <div class="sidebar">
        <div class="menu-item" onclick="navigate('colleges')">学院管理</div>
        <div class="menu-item" onclick="navigate('users')">用户管理</div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 面包屑导航 -->
        <div class="breadcrumb" id="breadcrumb">
            <a href="admin-colleges.html">学院管理</a> &gt;
            <span id="currentCollegeName">加载中...</span> - 管理员管理
        </div>

        <div class="page-header">
            <h2 class="page-title" id="pageTitle">学院管理员管理</h2>
            <div class="actions">
                <input type="text" class="search-box" id="searchInput" placeholder="搜索管理员...">
                <button class="btn" onclick="searchAdmins()">搜索</button>
                <button class="btn btn-primary" onclick="showAddAdminModal()">添加管理员</button>
                <button class="btn" onclick="loadAdmins()">刷新</button>
                <button class="btn" onclick="toggleDebug()" style="font-size: 12px;">调试</button>
            </div>
        </div>

        <!-- 调试信息 -->
        <div id="debugInfo" class="debug-info">
            <strong>调试信息:</strong>
            <div id="debugContent"></div>
        </div>

        <!-- 统计信息 -->
        <div class="stats" id="statsInfo">
            当前学院管理员总数：<strong id="adminCount">0</strong>
        </div>

        <!-- 管理员表格 -->
        <table id="adminTable">
            <thead>
            <tr>
                <th>姓名</th>
                <th>账号</th>
                <th>手机号</th>
                <th>创建时间</th>
                <th>状态</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="adminTableBody">
            <!-- 动态填充 -->
            </tbody>
        </table>

        <!-- 空状态 -->
        <div id="emptyState" class="empty-state" style="display: none;">
            <div>📋</div>
            <h3>暂无管理员</h3>
            <p>当前学院还没有管理员，点击"添加管理员"按钮来添加</p>
        </div>
    </div>
</div>

<!-- 添加管理员模态框 -->
<div id="addAdminModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>添加学院管理员</h3>
            <span class="close" onclick="closeAddAdminModal()">&times;</span>
        </div>
        <form id="addAdminForm">
            <div class="form-group">
                <label for="adminName">姓名 *</label>
                <input type="text" id="adminName" class="form-control" required>
            </div>
            <div class="form-group">
                <label for="adminAccount">账号 *</label>
                <input type="text" id="adminAccount" class="form-control" required>
            </div>
            <div class="form-group">
                <label for="adminTel">手机号</label>
                <input type="tel" id="adminTel" class="form-control">
            </div>
            <div class="form-group">
                <label for="adminPassword">初始密码</label>
                <input type="text" id="adminPassword" class="form-control" placeholder="留空则使用账号作为密码">
            </div>
        </form>
        <div class="modal-footer">
            <button class="btn" onclick="closeAddAdminModal()">取消</button>
            <button class="btn btn-primary" onclick="addAdmin()">确定</button>
        </div>
    </div>
</div>

<script>
    // 调试模式
    let debugMode = false;
    let currentCollegeId = null;
    let currentCollegeName = '';
    let admins = [];

    // 检查登录状态
    function checkLogin() {
        const token = localStorage.getItem('token');
        const role = localStorage.getItem('role');

        if (!token) {
            alert('请先登录');
            window.location.href = 'login.html';
            return false;
        }

        if (role !== 'Fr5g') {
            alert('无权访问此页面');
            window.location.href = 'login.html';
            return false;
        }

        return true;
    }

    // 获取认证头
    function getAuthHeaders() {
        const token = localStorage.getItem('token');
        return {
            'Content-Type': 'application/json',
            'token': token
        };
    }

    // 显示调试信息
    function showDebugInfo(message) {
        if (debugMode) {
            const debugContent = document.getElementById('debugContent');
            const timestamp = new Date().toLocaleTimeString();
            debugContent.innerHTML += `[${timestamp}] ${message}<br>`;
            console.log(message);
        }
    }

    // 切换调试模式（暴露为全局函数）
    window.toggleDebug = function() {
        debugMode = !debugMode;
        const debugInfo = document.getElementById('debugInfo');
        debugInfo.style.display = debugMode ? 'block' : 'none';
        showDebugInfo(`调试模式 ${debugMode ? '开启' : '关闭'}`);
    }

    // 处理API错误
    function handleApiError(response, error) {
        showDebugInfo(`HTTP状态: ${response.status} ${response.statusText}`);
        showDebugInfo(`请求URL: ${response.url}`);

        if (response.status === 401) {
            alert('登录已过期，请重新登录');
            logout();
            return true;
        } else if (response.status === 404) {
            showDebugInfo('错误: API接口不存在');
            alert('请求的接口不存在，请检查后端实现');
            return true;
        } else if (response.status === 500) {
            showDebugInfo('错误: 服务器内部错误');
            response.text().then(text => {
                showDebugInfo(`服务器错误详情: ${text}`);
            });
            alert('服务器内部错误，请查看后端日志');
            return true;
        } else if (!response.ok) {
            showDebugInfo(`错误: HTTP ${response.status}`);
            alert(`请求失败: ${response.status} ${response.statusText}`);
            return true;
        }

        if (error) {
            showDebugInfo(`错误: ${error.message}`);
        }
        return false;
    }

    // 页面加载
    document.addEventListener('DOMContentLoaded', function() {
        if (!checkLogin()) {
            return;
        }

        // 从URL参数获取学院信息
        const urlParams = new URLSearchParams(window.location.search);
        currentCollegeId = urlParams.get('collegeId');
        currentCollegeName = decodeURIComponent(urlParams.get('collegeName') || '');

        if (!currentCollegeId) {
            alert('无效的学院信息');
            window.location.href = 'admin-colleges.html';
            return;
        }

        updatePageTitle();
        loadAdmins();
    });

    // 更新页面标题和面包屑
    function updatePageTitle() {
        document.getElementById('pageTitle').textContent = `${currentCollegeName} - 管理员管理`;
        document.getElementById('currentCollegeName').textContent = currentCollegeName;
        document.getElementById('breadcrumb').innerHTML = `
            <a href="admin-colleges.html">学院管理</a> &gt;
            ${currentCollegeName} - 管理员管理
        `;
    }

    // 加载管理员列表
    async function loadAdmins() {
        showDebugInfo(`开始加载学院管理员列表，学院ID: ${currentCollegeId}`);

        try {
            const response = await fetch(`/api/admin/colleges/${currentCollegeId}/collegeadmins`, {
                method: 'GET',
                headers: getAuthHeaders()
            });

            showDebugInfo(`加载管理员列表响应状态: ${response.status}`);

            if (handleApiError(response)) return;

            const result = await response.json();
            showDebugInfo(`加载管理员列表响应数据: ${JSON.stringify(result)}`);

            if (result.code === 200) {
                // 关键修改：将id转为字符串
                admins = result.data.map(admin => ({
                    ...admin,
                    id: String(admin.id) // 强制转为字符串
                }));
                console.log("加载的管理员ID（字符串）:", admins.map(a => a.id)); // 控制台验证
                showDebugInfo(`成功加载 ${admins.length} 个管理员`);
                renderAdmins(admins);
                updateStats();
            } else {
                alert('加载管理员列表失败: ' + result.message);
                showDebugInfo(`加载失败: ${result.message}`);
            }
        } catch (error) {
            console.error('加载管理员列表失败:', error);
            showDebugInfo(`加载异常: ${error.message}`);
            alert('加载管理员列表失败');
        }
    }

    // 渲染管理员表格（修改：传递字符串ID和账号）
    function renderAdmins(adminList) {
        const tbody = document.getElementById('adminTableBody');
        const emptyState = document.getElementById('emptyState');

        if (adminList.length === 0) {
            tbody.innerHTML = '';
            emptyState.style.display = 'block';
            document.getElementById('adminTable').style.display = 'none';
            return;
        }

        emptyState.style.display = 'none';
        document.getElementById('adminTable').style.display = 'table';
        tbody.innerHTML = '';

        adminList.forEach(admin => {
            const adminId = admin.id; // 此时id已经是字符串
            const adminAccount = admin.account; // 获取账号
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${admin.name || '-'}</td>
                <td>${admin.account}</td>
                <td>${admin.tel || '-'}</td>
                <td>${formatDate(admin.createTime)}</td>
                <td>
                    <div class="action-buttons">
                        <button class="action-btn reset-btn" onclick="window.resetPassword('${adminId}', '${escapeHtml(admin.name)}', '${escapeHtml(admin.account)}')">重置密码</button>
                        <button class="action-btn remove-btn" onclick="window.removeAdmin('${adminId}', '${escapeHtml(admin.name)}')">移除</button>
                    </div>
                </td>
            `;
            tbody.appendChild(row);
        });
    }

    // 防XSS攻击的HTML转义
    function escapeHtml(unsafe) {
        if (!unsafe) return '';
        return unsafe.replace(/[&<>"']/g, function(m) {
            const entities = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#39;'
            };
            return entities[m];
        });
    }

    // 更新统计信息
    function updateStats() {
        document.getElementById('adminCount').textContent = admins.length;
    }

    // 搜索管理员
    function searchAdmins() {
        const keyword = document.getElementById('searchInput').value.toLowerCase();
        showDebugInfo(`搜索管理员关键词: ${keyword}`);
        const filtered = admins.filter(admin =>
            (admin.name && admin.name.toLowerCase().includes(keyword)) ||
            (admin.account && admin.account.toLowerCase().includes(keyword)) ||
            (admin.tel && admin.tel.includes(keyword))
        );
        showDebugInfo(`搜索到 ${filtered.length} 个管理员`);
        renderAdmins(filtered);
    }

    // 添加管理员模态框
    function showAddAdminModal() {
        document.getElementById('addAdminModal').style.display = 'block';
        document.getElementById('addAdminForm').reset();
    }

    function closeAddAdminModal() {
        document.getElementById('addAdminModal').style.display = 'none';
    }

    // 添加管理员
    async function addAdmin() {
        const name = document.getElementById('adminName').value.trim();
        const account = document.getElementById('adminAccount').value.trim();
        const tel = document.getElementById('adminTel').value.trim();
        const password = document.getElementById('adminPassword').value.trim();

        showDebugInfo(`开始添加管理员 - 姓名: ${name}, 账号: ${account}`);

        if (!name || !account) {
            alert('请填写姓名和账号');
            return;
        }

        const adminData = {
            name: name,
            account: account,
            tel: tel,
            password: password || account
        };

        try {
            const response = await fetch(`/api/admin/colleges/${currentCollegeId}/collegeadmins`, {
                method: 'POST',
                headers: getAuthHeaders(),
                body: JSON.stringify(adminData)
            });

            showDebugInfo(`添加管理员响应状态: ${response.status}`);

            if (handleApiError(response)) return;

            const result = await response.json();
            showDebugInfo(`添加管理员响应数据: ${JSON.stringify(result)}`);

            if (result.code === 200) {
                alert('添加成功');
                closeAddAdminModal();
                loadAdmins();
            } else {
                alert('添加失败: ' + result.message);
                showDebugInfo(`添加失败: ${result.message}`);
            }
        } catch (error) {
            console.error('添加管理员失败:', error);
            showDebugInfo(`添加异常: ${error.message}`);
            alert('添加管理员失败');
        }
    }

    // 重置密码（暴露为全局函数）- 使用账号重置
    window.resetPassword = function(userId, userName, userAccount) {
        console.log("重置密码操作 - 用户ID（字符串）:", userId, "账号:", userAccount); // 控制台打印验证
        showDebugInfo(`确认重置管理员 "${userName}" 的密码 - ID: ${userId}, 账号: ${userAccount}`);
        showDebugInfo(`请求URL: /api/admin/users/${userAccount}/password`);

        if (!confirm(`确定要重置管理员 "${userName}" 的密码吗？密码将重置为默认值。`)) {
            showDebugInfo('用户取消重置密码');
            return;
        }

        (async () => {
            try {
                // 使用账号重置密码的接口
                const response = await fetch(`/api/admin/users/${encodeURIComponent(userAccount)}/password`, {
                    method: 'PUT',
                    headers: getAuthHeaders()
                });

                showDebugInfo(`重置密码响应状态: ${response.status}`);

                if (handleApiError(response)) return;

                const result = await response.json();
                showDebugInfo(`重置密码响应数据: ${JSON.stringify(result)}`);

                if (result.code === 200) {
                    alert('密码重置成功');
                } else {
                    alert('密码重置失败: ' + result.message);
                    showDebugInfo(`重置失败: ${result.message}`);
                }
            } catch (error) {
                console.error('重置密码失败:', error);
                showDebugInfo(`重置异常: ${error.message}`);
                alert('重置密码失败');
            }
        })();
    }

    // 移除管理员（暴露为全局函数）
    window.removeAdmin = function(userId, userName) {
        console.log("移除操作 - 用户ID（字符串）:", userId); // 控制台打印验证
        showDebugInfo(`确认移除管理员 "${userName}" - ID: ${userId}`);
        showDebugInfo(`请求URL: /api/admin/colleges/${currentCollegeId}/collegeadmins/${userId}`);

        if (!confirm(`确定要移除管理员 "${userName}" 吗？此操作不可恢复！`)) {
            showDebugInfo('用户取消移除');
            return;
        }

        (async () => {
            try {
                const response = await fetch(`/api/admin/colleges/${currentCollegeId}/collegeadmins/${userId}`, {
                    method: 'DELETE',
                    headers: getAuthHeaders()
                });

                showDebugInfo(`移除管理员响应状态: ${response.status}`);

                if (handleApiError(response)) return;

                const result = await response.json();
                showDebugInfo(`移除管理员响应数据: ${JSON.stringify(result)}`);

                if (result.code === 200) {
                    alert('移除成功');
                    loadAdmins();
                } else {
                    alert('移除失败: ' + result.message);
                    showDebugInfo(`移除失败: ${result.message}`);
                }
            } catch (error) {
                console.error('移除管理员失败:', error);
                showDebugInfo(`移除异常: ${error.message}`);
                alert('移除失败');
            }
        })();
    }

    // 导航
    function navigate(page) {
        if (page === 'colleges') {
            window.location.href = 'admin-colleges.html';
        } else if (page === 'users') {
            window.location.href = 'admin-users.html';
        }
    }

    // 退出登录
    function logout() {
        if (confirm('确定要退出登录吗？')) {
            localStorage.removeItem('token');
            localStorage.removeItem('role');
            localStorage.removeItem('user');
            window.location.href = 'login.html';
        }
    }

    // 工具函数：格式化日期
    function formatDate(dateString) {
        if (!dateString) return '-';
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {
            hour: '2-digit',
            minute: '2-digit'
        });
    }

    // 点击模态框外部关闭
    window.onclick = function(event) {
        const modal = document.getElementById('addAdminModal');
        if (event.target === modal) {
            closeAddAdminModal();
        }
    }

    // 回车键搜索
    document.getElementById('searchInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            searchAdmins();
        }
    });
</script>
</body>
</html>